#include"tcp_server.h"
#include<string.h>
#include "config_file.h"

// 设置路由分发机制
// typedef void msg_callback(const char *data, uint32_t len, int msgid, net_connection* net_conn, void *args);
void call_back1(const char *data, uint32_t len, int msgid, net_connection* net_conn, void *args){
    printf("call_back1: msgid:%d, msglen:%d, msg:%s", msgid, len, data);
    net_conn->send_message(data, len, msgid);
}

void call_back2(const char *data, uint32_t len, int msgid, net_connection* net_conn, void *args){
    printf("call_back2: msgid:%d, msglen:%d, msg:%s", msgid, len, data);
    net_conn->send_message(data, len, msgid);

    printf("this is conn papam:%s", (char *)net_conn->param);

}

// 设置一般性任务
void task(event_loop* loop, void* args){
    static int num = 1;
    printf("thread:[%d] this is a putong task\n", num++);

    // 得到当前在线的fd都有哪些
    listen_fd_set fds;
    loop->get_fds(fds);
    
    for(auto& fd:fds){
        printf("online fd:[%d]\n", fd);
        tcp_conn* conn = tcp_server::conns[fd];
        if(conn != NULL){
            int msgid = 400;
            const char* data = "hello I am Task!\n";
            conn->send_message(data, strlen(data), msgid);
        }
    }
}

// 设置创建链接和关闭连接的hook函数
// typedef void (*conn_callback)(net_connection *conn, void *args);
void on_server_build(net_connection *conn, void *args){

    tcp_server* server = (tcp_server*)args;

    int msgid = 200;
    const char *data = "welcome you are online!\n";
    conn->send_message(data, strlen(data), msgid);
    
    // 一般性任务
    server->set_task(task);

    // 给当前的conn绑定一个自定义参数，供后续使用
    const char *papam = "I am the conn papam for you!\n";
    conn->param = (void *)papam;
}
void on_server_lost(net_connection *conn, void *args){
    printf("client are offline\n");
}


int main(){
    event_loop loop;

    // 加载配置文件
    config_file::setPath("./reactor.conf");
    std::string ip = config_file::instance()->GetString("reactor", "ip", "0.0.0.0");
    short port = config_file::instance()->GetNumber("reactor", "port", 8888);
    printf("ip: %s\tport: %d\n", ip.c_str(), port);

    // 允许连接的最大数
    int maxConn = config_file::instance()->GetNumber("reactor", "maxConn", 100);
    // 线程池个数，建议配置个数和CPU个数一致
    int thread_cnt = config_file::instance()->GetNumber("reactor", "threadNum", 3);  
    printf("maxConn: %d\tthread_cnt: %d\n", maxConn, thread_cnt);
    //创建套接字
    tcp_server server(&loop, ip.c_str(), port, maxConn, thread_cnt);

    // 注册msgid的回调函数 
    server.add_msg_router(1, call_back1);
    server.add_msg_router(2, call_back2);

    // 注册连接创建和删除的hook函数
    server.set_conn_start(on_server_build, (void*)&server);
    server.set_conn_close(on_server_lost);

    
    // 进入循环开始监听
    loop.event_process();

    return 0;
}
